import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Select, Button, Row, Col, Table, Space, Tag, Popconfirm, message, Dropdown, Tree, InputNumber, DatePicker } from 'antd';
import { SearchOutlined, ReloadOutlined, PlusOutlined, SettingOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { TablePaginationConfig } from 'antd/es/table';
import type { Dayjs } from 'dayjs';
import { productService } from './server';
import { Product, ProductStatus, ProductListParams } from './server';
import './index.less';

const { Option } = Select;

// 商品状态标签组件
const ProductStatusTag: React.FC<{ status?: ProductStatus }> = ({ status }) => {
  switch(status) {
    case ProductStatus.OnSale:
      return <Tag color="success">在售</Tag>;
    case ProductStatus.OutOfStock:
      return <Tag color="default">缺货</Tag>;
    case ProductStatus.Discontinued:
      return <Tag color="error">已下架</Tag>;
    default:
      return <Tag color="processing">草稿</Tag>;
  }
};

// 表格列定义
const getColumns = (
  handleEdit: (record: Product) => void,
  handleDelete: (id: string | number) => void
): ColumnsType<Product> => [
  {
    title: '商品图片',
    dataIndex: 'image',
    key: 'image',
    render: (image?: string) => (
      image ? <img src={image} alt="商品图片" style={{ width: 50, height: 50, objectFit: 'cover' }} /> : '-'
    ),
  },
  {
    title: '商品名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '商品编码',
    dataIndex: 'code',
    key: 'code',
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    render: (price?: number) => (price ? `¥${price.toFixed(2)}` : '-'),
  },
  {
    title: '库存',
    dataIndex: 'stock',
    key: 'stock',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: (status?: ProductStatus) => <ProductStatusTag status={status} />,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
    render: (_, record) => (
      <Space size="middle">
        <Button
          type="text"
          icon={<EditOutlined />}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>
        <Popconfirm
          title="确定删除该商品吗?"
          onConfirm={() => handleDelete(record.id)}
          okText="确定"
          cancelText="取消"
        >
          <Button 
            type="text" 
            danger 
            icon={<DeleteOutlined />}
          >
            删除
          </Button>
        </Popconfirm>
      </Space>
    ),
  },
];

// 可选的表单项
const formItems = [
  { label: '商品名称', key: 'name', component: <Input placeholder="请输入商品名称" /> },
  { label: '商品编码', key: 'code', component: <Input placeholder="请输入商品编码" /> },
  { 
    label: '商品分类', 
    key: 'category', 
    component: (
      <Select placeholder="请选择商品分类" allowClear>
        <Option value="电子产品">电子产品</Option>
        <Option value="服装">服装</Option>
        <Option value="家居">家居</Option>
        <Option value="食品">食品</Option>
        <Option value="图书">图书</Option>
      </Select>
    ) 
  },
  { 
    label: '商品状态', 
    key: 'status', 
    component: (
      <Select placeholder="请选择商品状态" allowClear>
        <Option value={ProductStatus.Draft}>草稿</Option>
        <Option value={ProductStatus.OnSale}>在售</Option>
        <Option value={ProductStatus.OutOfStock}>缺货</Option>
        <Option value={ProductStatus.Discontinued}>已下架</Option>
      </Select>
    ) 
  },
  {
    label: '价格范围',
    key: 'priceRange',
    component: (
      <Space style={{ width: '100%' }}>
        <Form.Item name={['priceRange', 0]} noStyle>
          <InputNumber style={{ width: '100%' }} placeholder="最低价" min={0} />
        </Form.Item>
        <span>-</span>
        <Form.Item name={['priceRange', 1]} noStyle>
          <InputNumber style={{ width: '100%' }} placeholder="最高价" min={0} />
        </Form.Item>
      </Space>
    )
  },
  {
    label: '库存范围',
    key: 'stockRange',
    component: (
      <Space style={{ width: '100%' }}>
        <Form.Item name={['stockRange', 0]} noStyle>
          <InputNumber style={{ width: '100%' }} placeholder="最低库存" min={0} />
        </Form.Item>
        <span>-</span>
        <Form.Item name={['stockRange', 1]} noStyle>
          <InputNumber style={{ width: '100%' }} placeholder="最高库存" min={0} />
        </Form.Item>
      </Space>
    )
  },
  {
    label: '创建时间',
    key: 'createTimeRange',
    component: <DatePicker.RangePicker style={{ width: '100%' }} />
  },
];

// 定义表单值类型
interface ProductFormValues {
  name?: string;
  code?: string;
  category?: string;
  status?: ProductStatus;
  priceRange?: [number | null, number | null];
  stockRange?: [number | null, number | null];
  createTimeRange?: [Dayjs, Dayjs];
}

export const ProductList: React.FC = () => {
  // 搜索表单
  const [form] = Form.useForm<ProductFormValues>();
  
  // 商品列表数据
  const [loading, setLoading] = useState<boolean>(false);
  const [data, setData] = useState<Product[]>([]);
  const [total, setTotal] = useState<number>(0);
  
  // 分页设置
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  
  // 搜索表单显示项配置
  const [visibleItems, setVisibleItems] = useState<string[]>(
    formItems.map(item => item.key)
  );
  const [showFormItemModal, setShowFormItemModal] = useState<boolean>(false);
  
  // 表单项配置对话框
  const FormItemConfig = () => (
    <div className="search-form-config">
      <Tree
        checkable
        defaultExpandAll
        checkedKeys={visibleItems}
        onCheck={(checkedKeys) => {
          setVisibleItems(checkedKeys as string[]);
          localStorage.setItem('productListSearchItems', JSON.stringify(checkedKeys));
          setShowFormItemModal(false);
        }}
        treeData={[
          {
            title: '搜索项',
            key: 'all',
            children: formItems.map(item => ({
              title: item.label,
              key: item.key,
            })),
          },
        ]}
      />
    </div>
  );

  // 加载数据
  const loadData = async (params: ProductListParams) => {
    setLoading(true);
    try {
      const response = await productService.getProductList(params);
      setData(response.list);
      setTotal(response.total);
    } catch (error) {
      console.error('获取商品列表失败:', error);
      message.error('获取商品列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载及表单项配置恢复
  useEffect(() => {
    // 从本地存储恢复搜索表单配置
    const savedItems = localStorage.getItem('productListSearchItems');
    if (savedItems) {
      try {
        const parsedItems = JSON.parse(savedItems);
        setVisibleItems(parsedItems);
      } catch (e) {
        console.error('解析保存的搜索项失败:', e);
      }
    }

    // 加载初始数据
    loadData({
      page: pagination.current,
      pageSize: pagination.pageSize,
    });
  }, []);

  // 表格变化处理
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    const values = form.getFieldsValue();
    
    // 基础查询参数
    const searchParams: ProductListParams = {
      page: newPagination.current || 1,
      pageSize: newPagination.pageSize || 10,
      keyword: values.name, 
      category: values.category,
      status: values.status,
    };

    // 处理价格范围
    if (values.priceRange?.[0]) {
      searchParams.minPrice = values.priceRange[0];
    }
    if (values.priceRange?.[1]) {
      searchParams.maxPrice = values.priceRange[1];
    }

    // 处理库存范围
    if (values.stockRange?.[0]) {
      searchParams.minStock = values.stockRange[0];
    }
    if (values.stockRange?.[1]) {
      searchParams.maxStock = values.stockRange[1];
    }

    // 处理创建时间范围
    if (values.createTimeRange?.[0]) {
      searchParams.startDate = values.createTimeRange[0].format('YYYY-MM-DD');
    }
    if (values.createTimeRange?.[1]) {
      searchParams.endDate = values.createTimeRange[1].format('YYYY-MM-DD');
    }
    
    setPagination({
      current: newPagination.current || 1,
      pageSize: newPagination.pageSize || 10,
    });
    
    loadData(searchParams);
  };

  // 搜索处理
  const handleSearch = () => {
    const values = form.getFieldsValue();
    
    // 基础查询参数
    const searchParams: ProductListParams = {
      page: 1,
      pageSize: pagination.pageSize,
      keyword: values.name,
      category: values.category,
      status: values.status,
    };

    // 处理价格范围
    if (values.priceRange?.[0]) {
      searchParams.minPrice = values.priceRange[0];
    }
    if (values.priceRange?.[1]) {
      searchParams.maxPrice = values.priceRange[1];
    }

    // 处理库存范围
    if (values.stockRange?.[0]) {
      searchParams.minStock = values.stockRange[0];
    }
    if (values.stockRange?.[1]) {
      searchParams.maxStock = values.stockRange[1];
    }

    // 处理创建时间范围
    if (values.createTimeRange?.[0]) {
      searchParams.startDate = values.createTimeRange[0].format('YYYY-MM-DD');
    }
    if (values.createTimeRange?.[1]) {
      searchParams.endDate = values.createTimeRange[1].format('YYYY-MM-DD');
    }

    setPagination({ ...pagination, current: 1 });
    loadData(searchParams);
  };

  // 重置处理
  const handleReset = () => {
    form.resetFields();
    setPagination({ ...pagination, current: 1 });
    loadData({
      page: 1,
      pageSize: pagination.pageSize,
    });
  };

  // 编辑商品
  const handleEdit = (record: Product) => {
    // 跳转到编辑页面或打开编辑对话框
    message.info(`编辑商品: ${record.name}`);
  };

  // 删除商品
  const handleDelete = async (id: string | number) => {
    try {
      await productService.deleteProduct(id);
      message.success('删除成功');
      loadData({
        ...form.getFieldsValue(),
        page: pagination.current,
        pageSize: pagination.pageSize,
      });
    } catch (error) {
      console.error('删除商品失败:', error);
      message.error('删除商品失败');
    }
  };

  // 新建商品
  const handleCreate = () => {
    // 跳转到新建页面或打开新建对话框
    message.info('新建商品');
  };

  return (
    <div className="product-list-container">
      {/* 搜索表单 */}
      <Card className="search-form-card">
        <Form
          form={form}
          layout="horizontal"
          onFinish={handleSearch}
        >
          <Row gutter={[16, 16]}>
            {formItems
              .filter(item => visibleItems.includes(item.key))
              .map((item) => (
                <Col span={6} key={item.key}>
                  <Form.Item label={item.label} name={item.key}>
                    {item.component}
                  </Form.Item>
                </Col>
              ))
            }
            <Col span={6} style={{ display: 'flex', alignItems: 'flex-end' }}>
              <Form.Item>
                <Space>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    icon={<SearchOutlined />}
                  >
                    搜索
                  </Button>
                  <Button 
                    onClick={handleReset}
                    icon={<ReloadOutlined />}
                  >
                    重置
                  </Button>
                  <Button 
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleCreate}
                  >
                    新建
                  </Button>
                  <Dropdown
                    overlay={<FormItemConfig />}
                    open={showFormItemModal}
                    onOpenChange={setShowFormItemModal}
                    trigger={['click']}
                  >
                    <Button 
                      icon={<SettingOutlined />}
                      onClick={() => setShowFormItemModal(true)}
                    >
                      配置
                    </Button>
                  </Dropdown>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      {/* 数据表格 */}
      <Card className="data-table-card">
        <Table
          columns={getColumns(handleEdit, handleDelete)}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          onChange={handleTableChange}
        />
      </Card>
    </div>
  );
}; 